<template>
  <span class="base-xgplayer bg-tr" :class="{ 'hide-center-btn': hideCenterBtn }">
    <span
      v-if="config.poster && lazy && showImg"
      style="width: 100%; height: 100%"
      class="center"
      @click="handleClick"
    >
      <img :src="config.poster" style="max-height: 100%; max-width: 100%" />
      <span class="img-play">
        <svg xmlns="http://www.w3.org/2000/svg" width="70" height="70" viewBox="0 0 70 70">
          <path
            transform="translate(15,15) scale(0.04,0.04)"
            d="M576,363L810,512L576,661zM342,214L576,363L576,661L342,810z"
          ></path>
        </svg>
      </span>
    </span>
    <div v-else :id="uuid"></div>
  </span>
</template>

<script setup>
import Player from "xgplayer";
import 'xgplayer/dist/index.min.css'
import { sleep } from "../utils";
import { usePureListenersAndAttr } from "@/utils";

const props = defineProps({
  /** @name 结束后重新开始，这里的重新开始指直接跳回封面 */
  endRestart: {
    type: Boolean,
    default: false,
  },
  /** @name 西瓜视频配置: https://v2.h5player.bytedance.com/config */
  config: {
    type: Object,
    default: () => ({}),
  },
  /** @name 是否直接加载视频，lazy代表用封面代替视频，在渲染大列表的时候有用 */
  lazy: {
    type: Boolean,
    default: true,
  },
  /** @name 是否隐藏中间播放按钮，默认显示，通过CSS方式隐藏 */
  hideCenterBtn: {
    type: Boolean,
    default: false,
  },
  preload: {
    type: String,
    default: "metadata",
  },
});
const emits = defineEmits(["player", "search", "reset"]);

let player = ref(null);
let showImg = ref(props.lazy);
const uuid = useId();
// 获取全部listeners
const { pureListeners } = usePureListenersAndAttr();

onMounted(() => {
  !props.lazy && init();
});

async function init() {
  if (props.config?.url !== "") {
    const isFirstLoaded = !player;
    player.value = new Player({
      keyShortcut: "off",
      ...props.config,
      poster: null,
      id: uuid,
    });
    emits("player", player.value);
    player.value.video.setAttribute("preload", props.preload);
    // 设置原生视频封面，不用西瓜播放器的封面
    if (props.endRestart) {
      player.value.once("ended", ended);
    }
    if (isFirstLoaded && props.lazy) {
      // 解决抖动的问题
      await sleep();
    }
    if (props.config.poster) player.value.video.setAttribute("poster", props.config.poster);
    // 添加监听事件
    Object.keys(pureListeners).forEach((key) => {
      player.value.on(key, (...args) => pureListeners[key](player, ...args));
    });
  }
}

function ended() {
  props.config.poster = props.config.poster + "?time=" + new Date().getTime();
  player.value.destroy(true);
  init();
}

function play() {
  player?.value?.video?.play();
}

function pause() {
  player?.value?.video?.pause();
}

async function handleClick() {
  showImg.value = false;
  await nextTick();
  await init();
  player.value.video.play();
}

defineExpose({
  play,
  pause,
  player,
  handleClick,
});

onBeforeUnmount(() => {
  player && typeof player.destroy === "function" && player.destroy();
  player = null;
});
</script>

<style lang="scss" scoped>
.base-xgplayer {
  text-align: center;
  width: 100%;
  height: 100%;
  display: inline-block;
  position: relative;
  .img-play {
    background: rgba(0, 0, 0, 0.38);
    color: #fff;
    font-size: 40px;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    width: 70px;
    height: 70px;
    border-radius: 50%;
    position: absolute;
    left: 50%;
    top: 50%;
    z-index: 115;
    margin: -35px auto auto -35px;
    svg {
      fill: hsla(0, 0%, 100%, 0.7);
    }
  }
  &.hide-center-btn {
    :deep() {
      .xgplayer-start {
        display: none !important;
      }
    }
  }
}
</style>
